<script setup>
import { ref, reactive, computed, onUpdated } from 'vue';
import { getsectorsApi, addsectorApi, editsectorApi, delsectorApi } from '@/api/sectors';
import { useUserStore, useSectorsStore } from "@/stores/counter";
import { showNetError, timestampToTime } from '@/public/public.js'
import AddSectorDialog from '@/components/AddSectorDialog.vue'
import { showMessage } from '@/public/public';


const userStore = useUserStore();
const userMsg = computed(() => {
    return userStore.userMsg;
})

const token = userStore.userMsg.token;

const sectorsStore = useSectorsStore();
const sectorsMsg = computed(() => {
    return sectorsStore.sectorsMsg;
})

let currentOneData = reactive({});

let tableData = reactive([]);

//定义列表每页显示的条数
const pageSize = ref(10);
let currentPageData = ref([]);
//记住当前页面 使用的分页组件是从1计数开始的，为了与分页组件统一，申明的变量也从1开始
let currentPage = 1;

getsectorsApi(token).then((res)=>{
    console.log(res);
    const resData = res.data;
    if (resData.code === 0) { //重新登录
        showMessage(resData.msg, 'error', 3000);
        return;
    }
    const sectorsArr = [];
    if (!resData.data) {
        console.log(resData.data);
        return;
    } else {
        resData.data.forEach((val, idx) => {
            tableData.push({
                allStaff: val.allStaff,
                manage: val.manage,
                sectorId: val.sectorId,
                sectorName: val.sectorName,
                addTime: timestampToTime(val.addTime),
                staffNum: val.allStaff.length,
            });

            sectorsArr.push({
                sectorId: val.sectorId,
                sectorName: val.sectorName
            })
        });

        localStorage.setItem('sectorsMsg', JSON.stringify(sectorsArr));
        sectorsStore.change_sectorsMsg(sectorsArr);

        currentPageData.value = tableData.slice(0, pageSize.value);
    }
})

// 以下为分页功能
//page-size 改变时触发
function change_size(val) {
    console.log('change_size', val);
    currentPage = val;
    currentPageData.value = tableData.slice(pageSize.value * (currentPage - 1), pageSize.value * currentPage);
}
//current-page 改变时触发	
function change_current(val) {
    console.log('change_current', val);
    currentPage = val;
    currentPageData.value = tableData.slice(pageSize.value * (currentPage - 1), pageSize.value * currentPage);
}
//用户点击上一页按钮改变当前页时触发	
function click_prev() {
    // console.log('click_prev');
}
//用户点击下一页按钮改变当前页时触发
function click_next() {
    // console.log('click_next');
}


//点击"添加部门" 按钮 出现对话框
const dialogFormVisible = ref(false);
const dialogType = ref('add-type');
function addSector(){
    currentOneData.sectorId = '';
    currentOneData.sectorName = '';

    dialogFormVisible.value = true;
    dialogType.value = 'add-type';
}
function isShow(val) {
    dialogFormVisible.value = val;
}

//点击 '编辑' 按钮
const handleEdit = (index, row) => {
    currentOneData.sectorId = row.sectorId;
    currentOneData.sectorName = row.sectorName;

    dialogFormVisible.value = true;
    dialogType.value = 'edit-type';
    // console.log(index, row);
}
//点击 '删除' 按钮
const handleDelete = (index, row) => {
    currentOneData.sectorId = row.sectorId;
    currentOneData.sectorName = row.sectorName;

    dialogFormVisible.value = true;
    dialogType.value = 'delete-type';
    // console.log(index, row)
}

//输入数据参考(测试使用):  组织部、宣传部、统战部、团委、秘书室、总务部、财务部、业务部、人事部、企划部、法律部、培训部、市场部、公关部、销售部、采购部、研发部、设计部、产品部、生产部、维修部、设备部
//点击"添加部门"后 出现对话框 点击对话框的"确认"进行数据请求
function addSectorData(newData) {
    const obj = {
        sectorName: newData.sectorName,
        staffNum: 0,
        token,
    };
    addsectorApi(obj).then((res)=>{
        console.log(res);
        const resData = res.data;
        if (resData.code === 2) {
            showMessage(resData.msg, 'success', 2000);

            const secData = resData.data[0];
            tableData.push({
                allStaff: secData.allStaff,
                manage: secData.manage,
                sectorId: secData.sectorId,
                sectorName: secData.sectorName,
                addTime: timestampToTime(secData.addTime),
                staffNum: secData.allStaff.length,
            });
            console.log(tableData);

            change_current(currentPage);

            getsectorsApi(token).then((res)=>{
                const resData = res.data;
                if (!resData.data) {
                    return;
                } else {
                    localStorage.setItem('sectorsMsg', JSON.stringify(res.data.data));
                    sectorsStore.change_sectorsMsg(res.data.data);
                }
            })

        } else {
            showMessage(resData.msg, 'warning', 2000);
        }
    }).catch(res=>{
        showNetError(res);
    })
}

// 点击"编辑"后出现对话框 点击对话框的"确认"进行数据请求
function editSectorData(sectorEditedData){
    const obj = {
        token,
        sectorId:sectorEditedData.sectorId,
        sectorName:sectorEditedData.sectorName
    }
    editsectorApi(obj).then(res =>{
        const resData = res.data;
        if(resData.code === 1){
            showMessage(resData.msg, 'success', 2000);
            tableData.forEach(val => {
                if(val.sectorId === sectorEditedData.sectorId){
                    val.sectorName = sectorEditedData.sectorName;
                }
            });
            getsectorsApi(token).then((res)=>{
                const resData = res.data;
                if (!resData.data) {
                    return;
                } else {
                    localStorage.setItem('sectorsMsg', JSON.stringify(res.data.data));
                    sectorsStore.change_sectorsMsg(res.data.data);
                }
            })

        }else if(resData.code === 3){
            showMessage(resData.msg, 'warning', 2000);
        }else{
            showMessage(resData.msg, 'error', 2000);
        }
    }).catch(res=>{
        showNetError(res);
    })
}

// 点击"删除"后出现对话框 点击对话框的"确认"进行数据请求
function deleteSectorData(sectorDelData){
    const obj = {
        token,
        sectorId:sectorDelData.sectorId
    }
    delsectorApi(obj).then(res=>{
        const resData = res.data;
        if(resData.code === 1){
            showMessage(resData.msg, 'success', 2000);
            tableData.forEach((val, idx) => {
                if(val.sectorId === sectorDelData.sectorId){
                    tableData.splice(idx, 1);
                }
            });

            change_current(currentPage);

            getsectorsApi(token).then((res)=>{
                const resData = res.data;
                if (!resData.data) {
                    return;
                } else {
                    localStorage.setItem('sectorsMsg', JSON.stringify(res.data.data));
                    sectorsStore.change_sectorsMsg(res.data.data);
                }
            })

        }else{
            showMessage(resData.msg, 'error', 2000);
        }
    })
}

</script>

<template>
    <div>
        <div class="accountheader">
            <h3>部门列表</h3>
            <el-button type="primary" @click="addSector" class="accountheader-addacc">添加部门</el-button>
        </div>

        <el-table :data="currentPageData" border style="width:90%" empty-text="暂无部门列表数据">
            <el-table-column prop="sectorName" label="部门名称" width="220" align="center" />
            <el-table-column prop="staffNum" label="员工数量" width="120" align="center" />
            <el-table-column prop="addTime" label="添加时间" width="220" align="center" />
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" link @click="handleEdit(scope.$index, scope.row)" class="el-btn-edit">编辑</el-button>
                    <el-button type="primary" link @click="handleDelete(scope.$index, scope.row)" class="el-btn-delete">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination small background 
        layout="prev, pager, next" 
        :total="tableData.length" 
        class="mt-4" 
        @size-change="change_size"
        @current-change="change_current" 
        @prev-click="click_prev" 
        @next-click="click_next" 
        :page-size="pageSize" 
        />
        <div style="height: 100px;"></div>

        <AddSectorDialog 
        :currentData="currentOneData"
        :dialogFormVisible="dialogFormVisible" 
        :dialogType="dialogType"
        @isShow="isShow" 
        @addNewData="addSectorData"
        @editData="editSectorData"
        @deleteData="deleteSectorData"
        ></AddSectorDialog>

    </div>
</template>


<style>
.accountheader {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.accountheader h3 {
    margin-left: 20px;
    height: 50px;
    line-height: 50px;
    color: var(--el-color-primary);
}

.accountheader-addacc {
    display: block;
    margin-right: 140px;
}
.el-pagination {
    margin: 0 auto;
    margin-top: 30px;
    width: 50%;
}
.el-btn-edit{
    font-size: 14px;
}
.el-btn-edit span{
    color: #555;
}
.el-btn-delete{
    font-size: 12px;
}
.el-btn-delete span{
    color: #c33;
}
</style>





